package com.springboot.hotel.controller.menu;
import com.springboot.hotel.model.SysUser;
import com.springboot.hotel.service.impl.SysUserServiceImpl;
import com.springboot.hotel.xencryption.MD5Util;
import com.springboot.hotel.xencryption.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.anji.captcha.util.AESUtil.aesDecrypt;

//admain菜单管理
@RestController
public class AdmainMenuController {
    @Autowired
    SysUserServiceImpl service;

    //    跳转页面到修改密码菜单管理
    @GetMapping("/admin/userPassword")
    public ModelAndView userPassword(HttpServletRequest request) {
        HttpSession session = request.getSession();
        SysUser one = (SysUser) session.getAttribute("sysUser");
        ModelAndView mv = new ModelAndView("/admin/userPassword", "user", one);
        return mv;
    }
    @PostMapping("/admin/userPasswordUpdate")
    public R editPassword(@RequestBody SysUser sysUser) {
//        获取session中的用户信息
        SysUser user = service.getById(sysUser.getId());
//        id
        sysUser.setId(user.getId());
//AES解密
        try {
            String old = aesDecrypt(sysUser.getOldPassword(),sysUser.getKey());
            String newP = aesDecrypt(sysUser.getNewPassword(),sysUser.getKey());
            String confirm = aesDecrypt(sysUser.getConfirmPassword(),sysUser.getKey());
// MD5加密
            String oldPassword = MD5Util.MD5(sysUser.getUsername(), old);
            String newPassword = MD5Util.MD5(sysUser.getUsername(), newP);
            String confirmPassword = MD5Util.MD5(sysUser.getUsername(),confirm);
//        判断旧密码是否正确
            if (!user.getPassword().equals(oldPassword)) {
                return R.fail("旧密码错误");
            }
//      判断新密码和旧密码是否相同
            if (newPassword.equals(oldPassword)) {
                return R.fail("新密码不能和旧密码相同");
            }
//        判断新密码和确认密码是否相同
            if (!newPassword.equals(confirmPassword)) {
                return R.fail("新密码和确认密码不相同");
            }
//      修改密码
            sysUser.setPassword(confirmPassword);
            boolean b = service.updateById(sysUser);
            if (b) {
                return R.ok("修改成功");
            } else {
                return R.fail("修改失败");
            }
        } catch (Exception e) {
            throw new RuntimeException("密码解密错误",e);
        }
    }
}
